package com.hewep.web.controller;

import java.io.File;
import java.util.List;

import com.hewep.kit.CacheKit;
import com.hewep.kit.TableKit;
import com.hewep.support.AjaxResult;
import com.hewep.support.PoiKit;
import com.hewep.support.excel.DefaultRowReader;
import com.hewep.support.excel.IRowReader;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;


public class IndexController extends BaseController {

	public void index() {
//		this.render("index.html");
		this.render("list.html");
	}
	
	public void load(){
		String type = this.getPara("type", "");
		
		this.render("list.html");
	}
	public void findAll(){
		AjaxResult result = new AjaxResult(1, "");
		try {
			List<Record> records = Db.find("select * from config");
			result.setData("tables", records);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setFailure(e.getMessage());
		}
		
		this.renderJson(result.toJson());
	}
	/**
	 * 分页
	 */
	public void pagination() {
		this.render("common/_pagination.html");
	}
	// 上传文件
	public void uploadHead(){
		AjaxResult result = new AjaxResult(1, "上传成功");
		try {
			UploadFile file = this.getFile("file");
			String tableName = this.getPara("table_name", "");
			String tempFilePath = PathKit.getWebRootPath() + "\\upload\\head.xlsx";
			File temp = new File(tempFilePath);
			if(temp.exists()){
				temp.delete();
			}
			file.getFile().renameTo(temp);
			if(Db.findFirst("select * from config where item = ?", tableName) == null){
				
				String json = PoiKit.readForJson(temp);
				String[] split = json.split("\\|");
				Db.update("insert into config(item, key_value, value_key) values(?,?,?)", tableName, split[0], split[1]);
				CacheKit.cacheByTableName(tableName,CacheKit.COLUMN_REMARK, split[0]);
				CacheKit.cacheByTableName(tableName,CacheKit.REMARK_COLUMN, split[1]);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setFailure("上传失败");
		}
		this.renderJson(result.toJson());
	}
	
}
